package com.codeest.geeknews.ui.gank.fragment;

import android.annotation.SuppressLint;
import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.Target;
import com.codeest.geeknews.R;
import com.codeest.geeknews.app.Constants;
import com.codeest.geeknews.base.BaseFragment;
import com.codeest.geeknews.base.contract.gank.GirlContract;
import com.codeest.geeknews.model.bean.GankItemBean;
import com.codeest.geeknews.model.bean.PhotoBean;
import com.codeest.geeknews.presenter.gank.GirlPresenter;
import com.codeest.geeknews.ui.gank.adapter.GirlAdapter;
import com.codeest.geeknews.ui.main.activity.PhotoDetailActivity;
import com.codeest.geeknews.util.convert.BeanConvertor;
import com.codeest.geeknews.util.convert.FieldFilter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;

/**
 * Created by codeest on 16/8/19.
 */

public class GirlFragment extends BaseFragment<GirlPresenter> implements GirlContract.View {

    @BindView(R.id.view_main)
    RecyclerView rvGirlContent;
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout swipeRefresh;

    private static final int SPAN_COUNT = 2;

    GirlAdapter mAdapter;
    ArrayList<GankItemBean> mList;
    LinearLayoutManager mStaggeredGridLayoutManager;


    private boolean isLoadingMore = false;
    private ArrayList<PhotoBean> mImageList;
    private int clickPosition;
    private View shareImageView;

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.view_common_list;
    }

    @Override
    protected void initEventAndData() {
        mList = new ArrayList<>();
        mAdapter = new GirlAdapter(mContext, mList);
        mStaggeredGridLayoutManager = new LinearLayoutManager(getActivity());
        mStaggeredGridLayoutManager.setItemPrefetchEnabled(false);
        rvGirlContent.setLayoutManager(mStaggeredGridLayoutManager);
        rvGirlContent.setAdapter(mAdapter);
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.getGirlData();
            }
        });
        rvGirlContent.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastItem = mStaggeredGridLayoutManager.findFirstVisibleItemPosition();
                if (lastItem > mAdapter.getItemCount() - 5 && !isLoadingMore && dy > 0) {
                    isLoadingMore = true;
                    mPresenter.getMoreGirlData();
                }
            }
        });
        //
        /*mAdapter.setOnItemClickListener(new GirlAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(int position, View shareView) {
                //转换对象
                BeanConvertor convertor = new BeanConvertor();
                ArrayList<PhotoBean> mImageList = convertor.convert(mList, PhotoBean.class, new FieldFilter() {
                    @Override
                    public String[] fromFields() {
                        return new String[]{"_id", "url"};
                    }

                    @Override
                    public String[] toFields() {
                        return new String[]{"id", "url"};
                    }
                });
                Intent intent = new Intent();
                //com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable cannot be cast to android.graphics.drawable.BitmapDrawable
                PhotoDetailActivity.bitmap = ((GlideBitmapDrawable) ((ImageView) shareView).getDrawable()).getBitmap();
                //PhotoDetailActivity.bitmap = ((GlideBitmapDrawable) ((ImageView) shareView).getDrawable()).getBitmap();
                //PhotoDetailActivity.bitmap = ImageUtil.getBitmapFromDrawable(shareView.getBackground());
                intent.setClass(mContext, PhotoDetailActivity.class);
                intent.putExtra(Constants.IT_PHOTO_CLICK_POSITION, position);
                intent.putParcelableArrayListExtra(Constants.IT_PHOTO_INFOS, mImageList);
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    ActivityOptions options = null;
                    options = ActivityOptions.makeSceneTransitionAnimation(mActivity, shareView, "shareView");
                    mContext.startActivity(intent, options.toBundle());
                } else {
                    mContext.startActivity(intent);
                }

            }
        });*/
        mAdapter.setOnItemClickListener(new GirlAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(final int position, final View shareView) {
                //转换对象
                BeanConvertor convertor = new BeanConvertor();
                /*final ArrayList<PhotoBean> */
                mImageList = convertor.convert(mList, PhotoBean.class, new FieldFilter() {
                    @Override
                    public String[] fromFields() {
                        return new String[]{"_id", "url"};
                    }

                    @Override
                    public String[] toFields() {
                        return new String[]{"id", "url"};
                    }
                });
                clickPosition = position;
                shareImageView = shareView;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            PhotoDetailActivity.bitmap = Glide.with(mActivity)
                                    .load(mList.get(position).getUrl())
                                    .asBitmap()
                                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                                    .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                                    .get();
                            mHandler.sendEmptyMessage(0);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();


            }
        });
        stateLoading();
        mPresenter.getGirlData();
    }

    @Override
    public void stateError() {
        super.stateError();
        if (swipeRefresh.isRefreshing()) {
            swipeRefresh.setRefreshing(false);
        }
    }

    @Override
    public void showContent(List<GankItemBean> list) {
        if (swipeRefresh.isRefreshing()) {
            swipeRefresh.setRefreshing(false);
        }
        stateMain();
        mList.clear();
        mList.addAll(list);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void showMoreContent(List<GankItemBean> list) {
        isLoadingMore = false;
        mList.addAll(list);
        for (int i = mList.size() - GirlPresenter.NUM_OF_PAGE; i < mList.size(); i++) {    //使用notifyDataSetChanged已加载的图片会有闪烁，遂使用inserted逐个插入
            mAdapter.notifyItemInserted(i);
        }
    }

    @Override
    public void onDestroy() {
        mHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Intent intent = new Intent();
            intent.setClass(mContext, PhotoDetailActivity.class);
            intent.putExtra(Constants.IT_PHOTO_CLICK_POSITION, clickPosition);
            intent.putParcelableArrayListExtra(Constants.IT_PHOTO_INFOS, mImageList);
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                ActivityOptions options = null;
                options = ActivityOptions.makeSceneTransitionAnimation(mActivity, shareImageView, "shareView");
                mContext.startActivity(intent, options.toBundle());
            } else {
                mContext.startActivity(intent);
            }
        }
    };
}
